package com.zust513.service.impl;

import com.zust513.dto.CourierDTO;
import com.zust513.mapper.CourierMapper;
import com.zust513.service.CourierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 配送员服务实现类
 */
@Service
public class CourierServiceImpl implements CourierService {

    @Autowired
    private CourierMapper courierMapper;

    @Override
    public List<CourierDTO> getAllCouriers() {
        List<Map<String, Object>> courierMaps = courierMapper.findAllCouriers();
        List<CourierDTO> courierDTOs = new ArrayList<>();

        for (Map<String, Object> map : courierMaps) {
            CourierDTO dto = mapToCourierDTO(map);

            // 获取配送员服务的区域
            // 安全处理courier_id的类型转换
            Object courierId = map.get("courier_id");
            Integer courierIdInt = null;

            if (courierId instanceof Long) {
                courierIdInt = ((Long) courierId).intValue();
            } else if (courierId instanceof Integer) {
                courierIdInt = (Integer) courierId;
            }

            if (courierIdInt != null) {
                List<Map<String, Object>> regionMaps = courierMapper.findRegionsByCourierId(courierIdInt);
                List<String> regions = regionMaps.stream()
                        .map(regionMap -> (String) regionMap.get("name"))
                        .collect(Collectors.toList());
                dto.setRegions(regions);
            } else {
                dto.setRegions(new ArrayList<>());
            }

            courierDTOs.add(dto);
        }

        return courierDTOs;
    }

    @Override
    public CourierDTO getCourierById(Integer courierId) {
        Map<String, Object> courierMap = courierMapper.findCourierById(courierId);
        if (courierMap == null) {
            return null;
        }

        CourierDTO dto = mapToCourierDTO(courierMap);

        // 获取配送员服务的区域
        List<Map<String, Object>> regionMaps = courierMapper.findRegionsByCourierId(courierId);
        List<String> regions = regionMaps.stream()
                .map(regionMap -> (String) regionMap.get("name"))
                .collect(Collectors.toList());
        dto.setRegions(regions);

        return dto;
    }

    @Override
    public boolean updateCourierAuditStatus(Integer courierId, String status) {
        return courierMapper.updateAuditStatus(courierId, status) > 0;
    }

    @Override
    public List<Map<String, Object>> getOrdersByRegionAndTime(Integer regionId, LocalDateTime startTime, LocalDateTime endTime) {
        return courierMapper.findOrdersByRegionAndTime(regionId, startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> getUserOrders(Integer userId) {
        return courierMapper.findOrdersByUserId(userId);
    }

    /**
     * 将Map转换为CourierDTO
     */
    private CourierDTO mapToCourierDTO(Map<String, Object> map) {
        CourierDTO dto = new CourierDTO();

        // 修改类型转换方式，避免直接强制转换Long到Integer
        Object courierId = map.get("courier_id");
        if (courierId instanceof Long) {
            dto.setCourierId(((Long) courierId).intValue());
        } else if (courierId instanceof Integer) {
            dto.setCourierId((Integer) courierId);
        }

        Object userId = map.get("user_id");
        if (userId instanceof Long) {
            dto.setUserId(((Long) userId).intValue());
        } else if (userId instanceof Integer) {
            dto.setUserId((Integer) userId);
        }

        dto.setUsername((String) map.get("username"));
        dto.setPhone((String) map.get("phone"));
        dto.setEmail((String) map.get("email"));

        Object totalOrders = map.get("total_orders");
        if (totalOrders instanceof Long) {
            dto.setTotalOrders(((Long) totalOrders).intValue());
        } else if (totalOrders instanceof Integer) {
            dto.setTotalOrders((Integer) totalOrders);
        }

        dto.setCurrentStatus((String) map.get("current_status"));
        dto.setAuditStatus((String) map.get("audit_status"));
        dto.setCreatedAt((LocalDateTime) map.get("created_at"));
        dto.setLastLogin((LocalDateTime) map.get("last_login"));
        return dto;
    }

    @Override
    public Integer getTotalCouriersCount() {
        return courierMapper.getTotalCouriersCount();
    }
}
